import React,{Component} from 'react'
import Dropzone from 'react-dropzone'
import $ from 'jquery'
import { message,Spin} from 'antd';
import {browserHistory} from 'react-router'
import * as pub from '../../config/public'
import * as fetch from '../../config/fetch'

let sub_type = 1;
class SingleQuestion extends Component {
	constructor(args) {
		super();
	}
	delThis(number){
		$('#SingleQuestion' + number).remove();
	}
	render(){
		return(
			<div className="topic-cont SingleQuestion" id={'SingleQuestion' + this.props.number}>
				<h5><label>
				题目</label>
				<input required="required" className="question" type="text"/> <a className='delete-question' onClick={()=>this.delThis(this.props.number)}><i className='icon-trash'></i></a></h5>
				<dl className="clearFix mar-t-20">
					<dt>选项</dt>
					<dd>
						<ul>
							<li><label>A</label><input required="required" className="describeA" type="text"/></li>
							<li><label>B</label><input required="required" className="describeB" type="text"/></li>
							<li><label>C</label><input required="required" className="describeC" type="text"/></li>
							<li><label>D</label><input required="required" className="describeD" type="text"/></li>
						</ul>
					</dd>
				</dl>
				<dl className="clearFix mar-t-20">
					<dt>答案</dt>
					<dd><label>
					<input  required="required" type="radio" name={'single_answer'+this.props.number}/>A</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>B</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>C</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>D</label></dd>
				</dl>
			</div>
			)
	}
}
class MultipleQuestion extends Component {
	constructor(args) {
		super();
	}
	delThis(number){
		$('#MultipleQuestion' + number).remove();
	}
	render(){
		return(
			<div  className="topic-cont MultipleQuestion" id={'MultipleQuestion' + this.props.number}>
				<h5><label>
				题目</label>
				<input required="required" className="question" type="text"/><a className='delete-question' onClick={()=>this.delThis(this.props.number)}><i className='icon-trash'></i></a></h5>
				<dl className="clearFix mar-t-20">
					<dt>选项</dt>
					<dd>
						<ul>
							<li><label>A</label><input required="required" className="describeA" type="text"/></li>
							<li><label>B</label><input required="required" className="describeB" type="text"/></li>
							<li><label>C</label><input required="required" className="describeC" type="text"/></li>
							<li><label>D</label><input required="required" className="describeD" type="text"/></li>
						</ul>
					</dd>
				</dl>
				<dl className="clearFix mar-t-20">
					<dt>答案</dt>
					<dd><label>
					<input type="checkbox"/>A</label><label>
					<input type="checkbox"/>B</label><label>
					<input type="checkbox"/>C</label><label>
					<input type="checkbox"/>D</label></dd>
				</dl>
			</div>
			)
	}
}
class AddCourse extends Component {
	constructor() {
		super()
		this.state = {
			videos: [],
			enclosures : [],
			singleNum: 0,
			multipleNum:0,
			loading: false,
			courseTypeName:[],
			courseType:'',
			categoriesList:[]
		}
	}
	chooseVideo(accepted, rejected) {
		if (accepted[0].size > 50 * 1024 * 1024) {
			message.error('视频大小不超过50MB', 3);
			return;
		}
		this.setState({
			videos: accepted
		});
	}
	changeVideo(e) {
		if (e.target.duration / 60 > 5) {
			message.error('视频不超过5分钟', 3);
			this.setState({
				videos: []
			})
		}
	}
	chooseEnclosure(accepted, rejected) {
		if (this.state.enclosures.length+accepted.length > 5) {
			message.error('附件不超过5个', 1);
			return;
		}
		for (var i = 0; i < accepted.length; i++) {
			if (accepted[i].size > 10 * 1024 * 1024) {
				message.error("单个文件大小不超过10MB")
				return;
			}
		}
		this.setState({
			enclosures: this.state.enclosures.concat(accepted)
		});
	}
	addSingle() {
		let singleNum = 0,
			multipleNum = 0;
		$('.SingleQuestion').each(function(i) {
			singleNum++;
		})
		$('.MultipleQuestion').each(function(i) {
			multipleNum++;
		})
		if ((singleNum + multipleNum) === 5) {
			message.error('考题不超过5道', 1);
			return;
		}
		this.setState({
			singleNum: this.state.singleNum + 1
		})
	}
	addMultiple() {
		let singleNum = 0,
			multipleNum = 0;
		$('.SingleQuestion').each(function(i) {
			singleNum++;
		})
		$('.MultipleQuestion').each(function(i) {
			multipleNum++;
		})
		if ((singleNum + multipleNum) === 5) {
			message.error('考题不超过5道', 1);
			return;
		}
		this.setState({
			multipleNum: this.state.multipleNum + 1
		})
	}
	add(e) {
		e.preventDefault();
		let SingleQuestion = [];
		let MultipleQuestion = [];

		$('.SingleQuestion').each(function(i) {
			let question = $(this).find('.question').val();
			let describeA = $(this).find('.describeA').val();
			let describeB = $(this).find('.describeB').val();
			let describeC = $(this).find('.describeC').val();
			let describeD = $(this).find('.describeD').val();
			let checkboxList = $(this).find("input[type='radio']");
			let answer = 0;
			checkboxList.each((index, el) => {
				if (el.checked) {
					switch (index) {
						case 0:
							answer += 1;
							break;
						case 1:
							answer += 2;
							break;
						case 2:
							answer += 4;
							break;
						case 3:
							answer += 8;
							break;
						default:
							break;
					}
				}
			})
			SingleQuestion.push({
				question,
				describeA,
				describeB,
				describeC,
				describeD,
				answer
			})
		})
		$('.MultipleQuestion').each(function(i) {
			let question = $(this).find('.question').val();
			let describeA = $(this).find('.describeA').val();
			let describeB = $(this).find('.describeB').val();
			let describeC = $(this).find('.describeC').val();
			let describeD = $(this).find('.describeD').val();
			let checkboxList = $(this).find("input[type='checkbox']");
			let answer = 0;
			checkboxList.each((index, el) => {
				if (el.checked) {
					switch (index) {
						case 0:
							answer += 1;
							break;
						case 1:
							answer += 2;
							break;
						case 2:
							answer += 4;
							break;
						case 3:
							answer += 8;
							break;
						default:
							break;
					}
				}
			})
			MultipleQuestion.push({
				question,
				describeA,
				describeB,
				describeC,
				describeD,
				answer
			})
		})
		let flag = false;
		for (let x of MultipleQuestion) {
			if (x.answer.length === 0) {
				flag = true;
				break;
			}
		}
		if (flag) {
			message.error('多选题中有答案未选择', 1);
			return;
		}



		if (this.state.videos.length > 0) {

		} else {
			message.error('请添加课程视频', 1);
			return;
		}


		let coursedata = {};
		let checkboxTitles = [];
		let radioTitles = [];


		coursedata.courseName = $('#course_name').val();;
		coursedata.courseDesc = $('#course_describe').val();;
		coursedata.courseChannel = $('#course_channel').val();
		coursedata.courseType = $('#course_type').val();
		if (SingleQuestion.length + MultipleQuestion.length > 0) {
			// if ($('#answer_time').val() === ''||$('#answer_time').val()<=0) {
            //     message.error('请输入合理的答题时间', 2);
			// 	return;
			// } else {
			// 	coursedata.answerTime = $('#answer_time').val();
			// }
           coursedata.answerTime =10;
		}
		if (sub_type === 1) {
			coursedata.checkState = 4; //保存为草稿
		} else {
			coursedata.checkState = 3; //提交审核
			if (SingleQuestion.length + MultipleQuestion.length !== 5) {
			    message.error('请提交5道考题', 2);
		     	return;
		     }
		}


		for (let x of SingleQuestion) {
			radioTitles.push({
				radioTitle: x.question,
				radioAnswerDesc: [x.describeA, x.describeB, x.describeC, x.describeD],
				radioAnswer: x.answer,
				radioTitleType: 1
			});
		}
		for (let x of MultipleQuestion) {
			checkboxTitles.push({
				checkboxTitle: x.question,
				checkboxAnswerDesc: [x.describeA, x.describeB, x.describeC, x.describeD],
				checkboxAnswer: x.answer,
				checkboxTitleType: 2
			});
		}

		let formData = new FormData();
		formData.append('radioTitles', JSON.stringify(radioTitles));
		formData.append('coursedata', JSON.stringify(coursedata));
		formData.append('checkboxTitles', JSON.stringify(checkboxTitles));
		formData.append('video', this.state.videos[0]);
		formData.append('operationType', 'mainPage');
		formData.append('behaviorDataType', 'menu');
		formData.append('userCode', JSON.parse(localStorage.getItem('user')).userCode);



		for (let x of this.state.enclosures) {
			formData.append('fileList', x);
		}
		pub.loading(this, true);
		fetch.addCourse(formData).then((data) => {
			if (data.result === 'RC100') {
				message.success('保存成功', 2);
				pub.jumpHistory.push('/CourseManage');
			} else {
				message.error(data.errMsg, 3);
			}
			pub.loading(this, false);
		}, (res) => {
			pub.reject(res);
			pub.loading(this, false);
		})


	}
	classTypes() {
		fetch.goodType({
			pid: 2
		}).then((data) => {
			if (data.result === 'RC100') {
				this.setState({
					categoriesList: data.categoriesList ? data.categoriesList : [],
				})
			} else {
				message.error(data.errMsg, 3);
				this.setState({
					categoriesList: []
				})
			}
		}, (res) => {
			this.setState({
				categoriesList: []
			})
			pub.reject(res);
		})
	}
	componentWillMount() {
		if (localStorage.getItem('user') === null) {
			pub.jumpHistory.push('/Login');
		} else {
			this.classTypes();
		}
	}
	componentDidMount() {
		$('#course_channel').find("option").eq(Number(pub.user.channelId)).attr("selected", true);
		$('#answer_time').val(10);
	}
	numberInput = (e) => {
		let value = e.target.value;
			e.target.value = value.replace(/[^\d]/g,'');
	} 
	sub(type) {
		sub_type = type;
	}
	DeleteFile(value){
		let file = this.state.enclosures;
		let data = [];
		for(let i in file){
			if(Number(i) !== Number(value)){
				data.push(file[i])
			}
		}
		this.setState({
			enclosures:data
		})
	}
	render(){
		return(
			<Spin spinning={this.state.loading} tip="提交中...">
			<form onSubmit={(e)=>this.add(e)}>
				<div className="panel-120 bg-FFFFFF box-shadow">
					<h3 className="course-title">课程信息</h3>
					<div className="row">

						{this.state.videos.length > 0 ?		
						<div>			
							<video src={this.state.videos[0].preview} 
					         controls="controls"   
					         className = "course_video"
					         onCanPlayThrough = {(e)=>this.changeVideo(e)}
					         // poster={require('../style/images/test2.png')} 
					         preload="auto">
					         您的浏览器不支持 video 标签。
					         </video>
					         <a className="choose-again" onClick={()=>{this.setState({videos:[]})}}>重新选择视频</a>
					    </div>
					    :
					 <Dropzone
					 //maxSize= {50*1024*1024}
					 multiple={false}
					 className='upload-video'
					 onDrop={this.chooseVideo.bind(this)}
					 accept="video/mp4"
					  >
						<div className="file-box">
							<label className="file-label"><i className="icon-upload-alt"></i><span>&nbsp;选择视频</span><p>或将视频拖放到此处</p></label>
							<p>上传格式MP4  时长3~5分钟   ≤50M</p>
							<p>禁止发布的视频内容  视频大小  视频规格  视频时长  高清视频  视频处理流程</p>
						</div>
						</Dropzone>
					}

						<dl className="info-inp clearFix">
							<dt>课程名称</dt>
							<dd><input type="text" required="required" id="course_name" maxLength="100" placeholder='不能超过100个字符'/></dd>
						</dl>

						<dl className="info-inp clearFix">
							<dt>课程渠道</dt>
							<dd>
								<select id='course_channel' disabled="disabled">
								     {pub.courseChannel.map((type,index)=>{
					     		     return(
					     		     	<option key={index} value={index}>{type}</option>
					     		     	)
					     	            })}
								</select>
							</dd>
						</dl>
						<dl className="info-inp clearFix">
							<dt>课程分类</dt>
							<dd>
								<select  id='course_type' value={this.state.courseType} onChange={(e)=>{this.setState({courseType:e.target.value})}}>
									{this.state.categoriesList.map((item,index)=>{
										return(
											<option key={index} value={item.code}>{item.name}</option>
											)
									})}
						       </select>
							</dd>
						</dl>


						<dl className="info-inp clearFix">
							<dt>课程描述</dt>
							<dd><textarea required="required" id="course_describe"></textarea></dd>
						</dl>


						<div className="file-box-1">

						    <Dropzone
					         // maxSize= {31457280}
					         className='upload-enclosure'
					         onDrop={this.chooseEnclosure.bind(this)}
							 accept=".xls,.doc,.txt,.pdf,.xlsx,.pptx,.ppt,.docx"
					          >
							<label className="file-label"><i className="icon-upload-alt"></i>上传附件</label>
							</Dropzone>
							{/* <input type='file' ></input> */}

							<span>（格式：doc/pdf/ppt/xls）</span>
							<p>
							{this.state.enclosures.map((item,index)=>{
								return(
									  <span  onClick={()=>this.DeleteFile(index)} id={`image${this.props.index}`} key={index}>{item.name}<span  className="trash" style={{color:'red'}}>(删除)</span></span>
									)
							})}
							</p>
						</div>
				
					</div>
				</div>

				<div className="panel-120 bg-FFFFFF box-shadow">
					<h3 className="course-title">考题信息</h3>

			
				    <div className="time-inp">答题时间
					  <input id='answer_time' type="number" disabled='true' onKeyUp={this.numberInput}/>分钟<spin style={{color:'red',marginLeft: '14px'}}>答题时间固定为10分钟</spin>
					</div>
	

					<div className="topic-inp mar-t-20">
						<h4>单项选择题：</h4>
						
						{pub.getObject(this.state.singleNum).map((item,index)=>{
							return(
								  	<SingleQuestion key={index} number={index + 1}/>
								)
						})}

					<a className="add-topic" onClick={()=>this.addSingle()}>
					  <i className="icon-plus-sign-alt"></i>新增一题(单选)
					</a>

                   </div>


					<div className="topic-inp">
						<h4>多项选择题：</h4>
						{pub.getObject(this.state.multipleNum).map((item,index)=>{
							return(
								  	<MultipleQuestion key={index} number={index + 1}/>
								)
						})}
						<a className="add-topic" onClick={()=>this.addMultiple()}>
						  <i className="icon-plus-sign-alt"></i>新增一题(多选)
						</a>
					</div>

					<div className="save-subm-btn text-center">
						<div onClick={()=>this.sub(1)} style={{display:"inline-block"}}><button type='submit' value='save' className="btn btn-blue">{this.state.loading?'提交中..':'保存草稿'}</button></div>
						<button onClick={()=>this.sub(2)} type='submit'  className="btn btn-blue">{this.state.loading?'提交中..':'提交审核'}</button>
					</div>

			    </div>

			</form>
			</Spin>
			)
	}
}

export default AddCourse;